package com.jmu.posms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jmu.posms.dao.UserMapper;
import com.jmu.posms.dto.AddUserInputDto;
import com.jmu.posms.exception.ServiceException;
import com.jmu.posms.pojo.User;
import com.jmu.posms.service.RoleService;
import com.jmu.posms.service.UserService;
import com.jmu.posms.util.CryptoUtil;
import com.jmu.posms.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RoleService roleService;

    @Override
    public Boolean register(AddUserInputDto addUserInputDto) {
        User user = new User();
        BeanUtils.copyProperties(addUserInputDto, user);
        log.info(String.valueOf(user));
        // 设置注册的时间
        String modifyDate = DateUtil.getDate();
        user.setModifyDate(modifyDate);

        // 用注册时间作为盐值
        // 明文密码进行md5 + salt + hash散列加密
        user.setPassword(CryptoUtil.md5Encode(user.getPassword(), modifyDate));

        // 调用dao层注册
        try {
            userMapper.insert(user);
        } catch (Exception e) {
            throw new ServiceException("600", "用户已存在");
        }

        return true;
    }

    @Override
    public User findByUserName(String userName) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName, userName);

        User user = userMapper.selectOne(queryWrapper);
        return user;
    }

    @Override
    public List<User> findListByUserName(String name){
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(User::getUserName, name);

        List<User> users = userMapper.selectList(queryWrapper);
        return users;
    }


}
